package com.itheima.controller;

import com.itheima.Pojo.Dept;
import com.itheima.Pojo.Result;
import com.itheima.Service.DeptService;
import com.itheima.annotation.LogOperation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j     //会自动生成log对象，用于打印日志
@RequestMapping("/depts")
@RestController
public class DeptControl {
    @Autowired    // 从IOC容器中，自动寻找bean对象，为该变量赋值-----依赖注入的实现
    private DeptService deptService ;
    @GetMapping  // 限制请求方式为get
    public Result getAll(){

        // 1.调用service，获取数据
        List<Dept> depts = deptService.list();
        // 响应数据
        return Result.success(depts);
    }

    @DeleteMapping
//    public Result delete(HttpServletRequest request){
//        String id = request.getParameter("id");
//        int idInt = Integer.parseInt(id);
//
//        return Result.success();
//    }
    public Result delete(Integer id){
        log.info("id = {}",id);
        deptService.delete(id);
        return Result.success();
    }

    /**
     * 新增部门
     * @param dept
     * @return
     */
    @PostMapping
    @LogOperation
    public Result add(@RequestBody Dept dept){
        log.info("dept={}",dept);
        deptService.addDept(dept);
        return Result.success();
    }

    /**
     * 数据回显
     * @param id
     * @return
     */

    @GetMapping("/{id}")
    public Result getDeptById(@PathVariable Integer id){
        log.info("id={}",id);
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }

    /**
     *修改部门
     * @param dept
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Dept dept){

        deptService.update(dept);
        return Result.success();
    }
}
